package org.easy4j.framework.web.startup;

import com.google.common.base.Preconditions;
import org.easy4j.framework.core.config.TransactionConfiguration;
import org.easy4j.framework.core.plugin.ScanPackageHelper;
import org.easy4j.framework.core.util.ArrayUtils;
import org.easy4j.framework.web.startup.config.AppConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bjliuyong
 * @version 1.0
 * @created date 15-12-19
 */
public class ApplicationContextUtils {

    private static ApplicationContext applicationContext ;


    public static WebApplicationContext createRootApplicationContext(){

        AnnotationAndXmlConfigWebApplicationContext rootAppContext = new AnnotationAndXmlConfigWebApplicationContext();

        rootAppContext.scan(ScanPackageHelper.getBasePackages());

        List<Class> classes = new ArrayList<Class>(3);
        classes.add(AppConfig.class);
        classes.add(TransactionConfiguration.class);
        Class<?>[] ret = new Class<?>[classes.size()];
        Class<?>[] configClasses =  classes.toArray(ret);

        if (!ObjectUtils.isEmpty(configClasses)) {
            rootAppContext.register(configClasses);
        }

        applicationContext = rootAppContext ;

        return rootAppContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext  ;
    }

    public static <E> E getBean(String beanName) {

        Preconditions.checkNotNull(applicationContext) ;
        return (E)applicationContext.getBean(beanName);
    }

}
